package edu.bupt.changelog.log;

import edu.bupt.changelog.demo.service.dto.QueryAgentRequest;
import edu.bupt.changelog.demo.service.mapper.LogAgentService;
import edu.bupt.changelog.history.HistoryRegistion;
import edu.bupt.changelog.history.anno.HistoryPut;
import edu.bupt.changelog.history.aop.ChangeSaver;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


// https://blog.csdn.net/u012098021/article/details/116802329
@Aspect
@Component
public class LogAop {

    @Resource
    private ChangeSaver changeSaver;

    public static final String INSERT = "insert";
    public static final String UPDATE = "update";
    public static final String DELETE = "delete";

    private static Map<String, Object[]> map = new HashMap<>();
    static {
        Object[] insertParams = new Object[]{QueryAgentRequest.class};
        map.put(INSERT,insertParams);
        Object[] updateParams = new Object[]{QueryAgentRequest.class};
        map.put(UPDATE,updateParams);
        Object[] deleteParams = new Object[]{QueryAgentRequest.class};
        map.put(DELETE,deleteParams);
    }

    @Pointcut("this(edu.bupt.changelog.demo.service.mapper.LogAgentService)")
    public void pointCut1() {}

    @Around("pointCut1()")
    public Object around(ProceedingJoinPoint joinPoint){
        System.out.println("=====================进入aop");

        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        String name = method.getName();
        Object[] theArgs = joinPoint.getArgs();
        Object[] objects = map.get(name);

        LogAnno logAnno = method.getAnnotation(LogAnno.class);
        boolean isChange = false;

        if(null!=objects && objects.length==theArgs.length && objects.length>0){
            boolean flag = true;
            for(int i=0;i<theArgs.length;i++){
                if(!theArgs[i].getClass().equals(objects[i])){
                    flag = false;
                }
            }
            if(flag){
                isChange=true;
            }
        } else if (logAnno!=null){
            isChange=true;
        }

        if(isChange){
            if(Collection.class.isAssignableFrom((Class)theArgs[0])){
                // 批量查询;
            }else {
                // 考虑单条查询,但是单条查询也分param是不是object;
            }

        }


        Object obj = null;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }


        return obj;
    }

}
